package com.sjtuy.galtxtreader.bookfile;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.sjtuy.galtxtreader.file.utils.createFileOverWrite;
import static com.sjtuy.galtxtreader.file.utils.deleteDir;
import static com.sjtuy.galtxtreader.file.utils.openFileInDir;

//将导入的图书转换成阅读器能够读取的模式
public class BookImportConverter {
    public final String[] SPLIT_PUNCTUATIONS = {"！”","？”","。”","！\"","？\"","。\"","！","？","。","”"};
    public final String CHAPTER_REGEX = "^第(.+)章\\b";
    private Pattern CHAPTER_PATTERN;
    File bookRootDir;
    File txt;
    File chapterDir;
    private BookSplitter bookSplitter;
    public BookImportConverter(File _bookRootDir){
        bookRootDir=_bookRootDir;
        chapterDir = openFileInDir(bookRootDir,"chapters");
        txt=openFileInDir(bookRootDir,"txt");
        CHAPTER_PATTERN = Pattern.compile(CHAPTER_REGEX);
        if(chapterDir.exists()&&chapterDir.isDirectory()){
            deleteDir(chapterDir);
        }else if(chapterDir.exists()){
            chapterDir.delete();
        }
        chapterDir.mkdir();
        bookSplitter = new NormalBookSplitter(CHAPTER_REGEX);
    }

    public void setBookSplitter(BookSplitter bookSplitter) {
        this.bookSplitter = bookSplitter;
    }

    public void setDialogSplitter(DialogSplitter dialogSplitter) {
        bookSplitter.setDialogSplitter(dialogSplitter);
    }

    public void split(){
        if(chapterDir.exists()&&chapterDir.isDirectory()){
            deleteDir(chapterDir);
        }else if(chapterDir.exists()){
            chapterDir.delete();
        }
        chapterDir.mkdir();
        File currentChapterFile;
        try {
            BufferedReader txtReader = new BufferedReader(new FileReader(txt));
            StringBuilder bookContent = new StringBuilder();
            String tmpString;
            while ((tmpString=txtReader.readLine())!=null){
                if(tmpString.length()>0)
                    bookContent.append(tmpString.trim()).append("\n");
            }
            List<StringBuffer> chapters = bookSplitter.split(bookContent.toString());
            int chapterNum=1;
            for(StringBuffer sb :chapters){
                currentChapterFile = createFileOverWrite(chapterDir,""+chapterNum);
                FileWriter fw = new FileWriter(currentChapterFile);
                fw.write(sb.toString());
                fw.close();
                ++chapterNum;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
